<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加分类按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addCatesBtn">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- 分类表格区域 -->
      <!-- 分类表格:data(设置数据源) :columns(设置表格中列配置信息) :selection-type(是否有复选框):expand-type(是否展开数据) show-index(是否设置索引列) index-text(设置索引列头)
      border(是否添加纵向边框) :show-row-hover(是否鼠标悬停高亮)-->
      <tree-table
        :columns="columns"
        :data="cateList"
        :selection-type="false"
        :expand-type="false"
        :show-index="true"
        :border="true"
        :show-row-hover="false"
        class="treeTable"
      >
        <!-- 是否有效区域， 设置对应的模板列： slot="isok"(与columns中设置的template一致) -->
        <template slot="isok" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color:lightgreen"
          ></i>
          <i class="el-icon-error" v-else style="color:red"></i>
        </template>
        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level===0">一级</el-tag>
          <el-tag size="mini" type="success" v-else-if="scope.row.cat_level===1">二级</el-tag>
          <el-tag size="mini" type="warning" v-else>三级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="opt" slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            @click="editGoodsCates(scope.row.cat_id)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="deleteBtn(scope.row.cat_id)"
          >删除</el-button>
        </template>
      </tree-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加商品分类的对话框 -->
    <el-dialog title="添加分类" :visible.sync="addGoodsCates" width="50%" @close="addGoodsCateClose">
      <el-form
        ref="addGoodsCatesRef"
        :model="addGoodsCatesForm"
        label-width="100px"
        :rules="addGoodsCatesRules"
      >
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="addGoodsCatesForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类：">
          <el-cascader
            v-model="selectedKeys"
            :options="parentCateList"
            expand-trigger="hover"
            @change="parentCateChanged"
            :props="cascaderProps"
            clearable
            change-on-select
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addGoodsCates = false">取 消</el-button>
        <el-button type="primary" @click="addGoodCatesInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 点击编辑商品分类的对话框 -->
    <el-dialog title="修改分类" :visible.sync="editGoodsCatesVisible" width="50%">
      <el-form
        :model="editGoodsCatesForm"
        :rules="addGoodsCatesRules"
        ref="editGoodsCatesRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editGoodsCatesForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editGoodsCatesVisible = false">取 消</el-button>
        <el-button type="primary" @click="editGoodsCatesInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类数据
      cateList: [],
      // 查询分类数据的条件
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      // 总数据条数
      total: 0,
      columns: [
        { label: '分类名称', prop: 'cat_name' },
        //type:'template'(将该列设置为模板列)，template:'isok'(设置该列模板的名称为isok)
        { label: '是否有效', prop: '', type: 'template', template: 'isok' },
        { label: '排序', prop: '', type: 'template', template: 'order' },
        { label: '操作', prop: '', type: 'template', template: 'opt' },
      ],
      //   添加商品分类规则验证
      addGoodsCatesRules: {
        cat_name: [
          { required: true, message: '请输入分类名称!', trigger: 'blur' },
        ],
      },
      addGoodsCates: false,
      //   添加商品的分类名称
      addGoodsCatesForm: {
        cat_name: '',
        cat_pid: 0,
        cat_level: 0,
      },
      parentCateList: [],
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      selectedKeys: [],
      editGoodsCatesVisible: false,
      editGoodsCatesForm: {},
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 发送请求 获取商品列表数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo,
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      //   将数据列表数据赋值给data
      this.cateList = res.data.result
      // 保存总数据条数
      this.total = res.data.total
    },
    // 点击分页每页条数触发事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      // 刷新列表
      this.getCateList()
    },
    // 当页码发生变化时触发
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      // 刷新页面
      this.getCateList()
    },
    // 添加分类按钮
    addCatesBtn() {
      this.getParentCateList()
      this.addGoodsCates = true
    },
    parentCateChanged() {
      //   console.log(this.selectedKeys)
      // 如果 selectedKeys 数组中的 length 大于0，证明选中的父级分类
      // 反之，就说明没有选中任何父级分类
      if (this.selectedKeys.length > 0) {
        // 父级分类的Id
        this.addGoodsCatesForm.cat_pid = this.selectedKeys[
          this.selectedKeys.length - 1
        ]
        // 为当前分类的等级赋值
        this.addGoodsCatesForm.cat_level = this.selectedKeys.length
      } else {
        // 父级分类的Id
        this.addGoodsCatesForm.cat_pid = 0
        // 为当前分类的等级赋值
        this.addGoodsCatesForm.cat_level = 0
      }
    },
    // 发送获取父级列表数据的请求
    async getParentCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 },
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.parentCateList = res.data
    },
    // 点击添加分类的对话框确定按钮
    addGoodCatesInfo() {
      //点击确定，完成添加分类
      // 预验证
      this.$refs.addGoodsCatesRef.validate(async (valid) => {
        if (!valid) return
        //发送请求完成添加分类
        const { data: res } = await this.$http.post(
          'categories',
          this.addGoodsCatesForm
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加分类失败')
        }
        this.getCateList()
        this.addGoodsCates = false
        this.$message.success('添加分类成功')
      })
    },
    // 关闭对话框之前重置表单
    addGoodsCateClose() {
      this.$refs.addGoodsCatesRef.resetFields()
      this.selectedKeys = []
      this.addGoodsCatesForm.cat_level = 0
      this.addGoodsCatesForm.cat_pid = 0
    },
    // 点击编辑分类名称按钮
    async editGoodsCates(id) {
      const { data: res } = await this.$http.get(`categories/${id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editGoodsCatesForm = res.data
      this.editGoodsCatesVisible = true
    },
    // 点击编辑分类对话框的确定按钮
    editGoodsCatesInfo() {
      // 预验证
      this.$refs.editGoodsCatesRef.validate(async (valid) => {
        if (!valid) return
        // 发送请求更新数据
        const { data: res } = await this.$http.put(
          `categories/${this.editGoodsCatesForm.cat_id}`,
          {
            cat_name: this.editGoodsCatesForm.cat_name,
          }
        )
        this.$message.success(res.meta.msg)
        // 刷新列表
        this.getCateList()
        this.editGoodsCatesVisible = false
      })
    },
    // 点击删除分类按钮
    async deleteBtn(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该项, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.error('已取消删除！')
      }
      // 发送请求确认删除
      const { data: res } = await this.$http.delete(`categories/${id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 刷新列表数据
      this.getCateList()
      this.$message.success(res.meta.msg)
    },
  },
}
</script>

<style lang="less" scoped>
.el-cascader {
  width: 100%;
}
</style>